#include "Server.h"

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

user_list *list = NULL;

void *pthread_server(void *arg)
{

    int sock = *((int *)arg);

    int recv_size = 0 ;
    char buf[1024];
    char user_name[128];
    char user_password[128];
    user_data my_user;

    while (1)
    {
        recv_size = recv(sock ,buf ,sizeof(buf) , 0);

        if (recv_size == 0)
        {
            printf("客户端终止\n");
            close(sock);
            pthread_exit(NULL);
        }
        
        if (NULL != strstr(buf , "register "))
        {
            sscanf(buf ,"register %s %s end",user_name ,user_password);


            strcpy(my_user.name , user_name);
            
            strcpy(my_user.password , user_password);

            my_user.sock = sock;

            pthread_mutex_lock(&mutex);

            tail_insert_tail(list,my_user);
            
            pthread_mutex_unlock(&mutex);

            continue;
        }
        
        else if (NULL != strstr(buf ,"log in "))
        {
            sscanf(buf , "log in %s %s end",user_name , user_password);


            strcpy(my_user.name ,user_name);

            strcpy(my_user.password, user_password);

            my_user.sock = sock;

            if (find_Sql_list(list , my_user))
            {
                send(sock , "登录成功" , strlen("登录成功"), 0 );
                break;
            }
            else
            {
                send(sock , "账号或密码错误",strlen("账号密码错误"), 0);
                continue;
            }
            
        }

        else
        {
            send(sock , "** 好好发", strlen("** 好好发"), 0);
            continue;
        }
        
    }
    
    send_all(my_user);
}

void send_all(user_data my_user)
{

    int recv_size = 0;
    char buf_recv[1024];
    char buf_send[1024];
    char user_name[128];
    char user_password[128];

    while (1)
    {
        memset(buf_recv , 0 , sizeof(buf_recv));

        recv_size = recv(my_user.sock , buf_recv ,sizeof(buf_recv) , 0);
        if (recv_size == 0)
        {
            pthread_mutex_lock(&mutex);

            pos_del_list(list , my_user);
            
            pthread_mutex_unlock(&mutex);

            close(my_user.sock);
            
            return ;
        }
        
        pthread_mutex_lock(&mutex);
        
        for (size_t i = 0; i < list->len; i++)
        {
            printf("11\n");

            memset(buf_send , 0 ,sizeof(buf_send));

            sprintf(buf_send ,"%s:%s" , my_user.name , buf_recv);

            if (!strcmp(my_user.name , list->data[i].name))
            {
                continue;
            }
            send(list->data[i].sock , buf_send ,strlen(buf_send) , 0);
        }
        
        pthread_mutex_unlock(&mutex);

    }
    
}